/*
 * @Author: 谢陈洁
 * @Date: 2025-05-26 09:50:47
 * @LastEditors: 谢陈洁
 * @LastEditTime: 2025-08-01 16:24:56
 * @Description: file content
 */
import router from '@/router'
import { getUserInfo, getUserPermissions, login } from '@/services/apis/system/user'
import { defineStore } from 'pinia'
import type { RouteRecordRaw } from 'vue-router'

export interface UserState {
  token: string
  userInfo: any
  hasAddedRoutes: boolean // 添加标志位
  dynamicMenus: any[] // 动态菜单
  permissionButtons: any[]
}

export const useUserStore = defineStore('user', {
  // 显式声明泛型参数以解决类型错误
  state: (): UserState => ({
    token: '',
    dynamicMenus: [], // 动态菜单
    permissionButtons: [], // 按钮权限
    userInfo: {},
    hasAddedRoutes: false // 初始化为 false
  }),
  getters: {
  },
  actions: {
    // 用户登录
    async userLogin(params: { username: string; password: string }) {
      try {
        const res = await login(params)
        this.token = res.token
        return res.token
      } catch (error) {
        return false
      }

    },
    // 用户信息
    async getUserInfo(flag = false) {
      if(!flag && this.userInfo && Object.keys(this.userInfo).length > 0) {
        return this.userInfo // 如果用户信息已存在，直接返回
      }
      // 这里可以添加获取用户信息的逻辑
      const res = await getUserInfo() // 假设 getUserInfo 返回用户信息
      if(res) {
        this.userInfo = res
        return res
      }
    },
    // 获取用户权限
    async getPermissions() {
      const {menus=[], buttons=[]} = await getUserPermissions()
      this.dynamicMenus = menus
      this.permissionButtons = buttons.map((item: any) => item.permission_code)
      return {menus, buttons}
    },
    setRoutes(routes: RouteRecordRaw[]) {
      this.dynamicMenus = routes
    },
    // 在 logout 时重置标志位
    logout() {
      this.userInfo = {}
      this.token = ''
      this.dynamicMenus = []
      this.permissionButtons = []
      this.hasAddedRoutes = false // 重置标志位
      this.$reset()
      this.clearPersistedData()
      router.push('/login')
    },

    // 清除持久化数据
    clearPersistedData(): void {
      localStorage.removeItem('user-store')
    },
    /**
     * 清除 Token 并移除持久化数据
     * 注意：当前未加密存储，存在安全风险，建议后续改造
     */
    resetToken() {
      this.token = ''
      localStorage.removeItem('token') // 手动清理 localStorage
    }
  },
  persist: true
})
